/* 
 *  Copyright 2012 CodeMagi, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.codemagi.servlets.content;

import com.codemagi.servlets.content.model.VanityUrl;
import com.codemagi.util.Utils;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.log4j.*;
import org.exolab.castor.jdo.Database;
import org.exolab.castor.jdo.OQLQuery;
import org.exolab.castor.jdo.PersistenceException;
import org.exolab.castor.jdo.QueryResults;

/**
 * Filter to redirects incoming requests to a CMS page
 * 
 *  @version 1.0
 *  @author August Detlefsen for CodeMagi, Inc.
 */
public class VanityUrlFilter extends com.codemagi.servlets.BaseFilter implements Filter {

    Logger log = Logger.getLogger(this.getClass());

    //MEMBERS --------------------------------------------------

    private HashMap vanityUrls = new HashMap(128);


    /**
     * Initialize the filter, create jdo connection, load vanity URLs from DB
     */
    public void init(FilterConfig config)
        throws ServletException {

	//get JDO instance from superclass
        super.init(config);

	//load the list of vanity URLs into a hash for speed
	Database db = null;
	
	try {
	    //begin transaction
	    db = getJDODatabase();
	    db.begin();

	    OQLQuery oql = db.getOQLQuery(" SELECT v FROM com.codemagi.servlets.content.model.VanityUrl v ");

	    QueryResults results = oql.execute(Database.ReadOnly);
	    
	    while (results.hasMore()) {
		VanityUrl v = (VanityUrl)results.next();
		vanityUrls.put(v.getVanityUrl(), v.getPageId());
	    }

	} catch (PersistenceException pe) {
	    log.debug("", pe);
	    //handlePersistenceException(db, pe, "Unable to load vanity URLs hash from database");

	} finally {
	    closeJDODatabase(db);

	}

	//put this filter in the application context so it can be accessed from other servlets
	application.setAttribute("VanityUrlFilter", this);
    }


    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
	throws ServletException, IOException {

	String requestUrl = ((HttpServletRequest)request).getServletPath();

	//remove the leading slash if necessary
	//	if (requestUrl.startsWith("/")) requestUrl = requestUrl.substring(1);
	log.debug("REQUEST URL: " + requestUrl );

	//determine if there is a page ID for this vanity URL
	Integer pageId = (Integer)vanityUrls.get(requestUrl);
	log.debug("PAGE ID:     " + pageId );

	//if there is a page ID, forward to that page
	if ( pageId != null ) {

	    // Get the request dispatcher -- request will be 
	    // dispatched to this URL.
	    RequestDispatcher rd = request.getRequestDispatcher("/page/" + pageId);

	    // Forward to requested URL
	    rd.forward(request, response);

	} else {
            chain.doFilter(request, response);
        }

	return;
    }


    public void addVanityUrl(String vanityUrl, Integer pageId) {
	if (!Utils.isEmpty(vanityUrl)) vanityUrls.put(vanityUrl, pageId);
    }


    public void removeVanityUrl(String vanityUrl) {
	if (!Utils.isEmpty(vanityUrl)) vanityUrls.remove(vanityUrl);
    }

}
